<template>
  <BaseContainer class="report-table-wrapper" v-loading="loading" element-loading-text="加载中..."
    element-loading-background="rgba(255, 255, 255, 0.8)">
    <div class="r-header">
      <p>养老机构综合运营补贴（喘息服务补贴）申请表</p>
      <p class="text-sm">
        （所属时间： <span class="text-underline">{{ model.year }}</span>年第<span class="text-underline">{{
          getCurrentQuarter(model.month) }}</span>季度）
      </p>
    </div>
    <ReportTable :column="dataListBase" :isDetail="isDetail" :moreNewsModel="moreNewsModel.organizationInfoPO"
      :baseModel="baseModel.organizationInfoPO" :model="modelData.organizationInfoPO" @change="handleSave">
    </ReportTable>
    <ReportTable :column="dataListStaff" :isDetail="isDetail" :moreNewsModel="moreNewsModel.staffPO"
      :baseModel="baseModel.staffPO" :model="modelData.staffPO" @change="handleSave"></ReportTable>
    <ReportTable :column="dataListApply" :isDetail="isDetail" :moreNewsModel="moreNewsModel.applicationContentXuanWuPO"
      :baseModel="baseModel.applicationContentXuanWuPO" :model="modelData.applicationContentXuanWuPO" @change="handleSave">
      <template v-slot:note>
        <div class="w-100 tr flex-column">
          <p class="fc">本机构承诺以上及所附数据资料真实有效，如有不实，愿承担相关处罚。</p>
          <div class="p-r-50">
            <p>负责人签名： （单位盖章）</p>
            <p style="padding-right: 3vw">年 月 日</p>
          </div>
        </div>
      </template>
    </ReportTable>
    <ReportTable :column="dataListFooter" :model="modelData" :baseModel="editData.applicationContentXuanWuPO"
      @change="handleSave">
      <template v-slot:opinion>
        <div class="w-100">
          <p>区民政局：（章）</p>
          <p style="padding-right: 3vw">年 月 日</p>
        </div>
      </template>
    </ReportTable>

    <el-drawer size="65%" append-to-body v-model="drawer" :with-header="false" @close="onClose">
      <practitioner :needPigeonhole="false" v-if="drawer" :nowRowData="model" :isComprehensiveQueries="false"
        :actionBtn="false" />
    </el-drawer>

    <OrgArchives ref="orgArchivesEl"></OrgArchives>

  </BaseContainer>
</template>

<script setup lang="ts">
import OrgArchives from '../../OrgArchives/index.vue'
import { onUnmounted } from 'vue'
import ReportTable from '../../ReportTable/index.vue'

import apiMod from '@/apiMod'
import practitioner from '../../../practitioner/index.vue'

import { useCommonStore } from '@/stores/common'
import { dealBigMoney, filterEmptyObj } from '@/utils/util'
const { setTempParams, setGloablParams, setMoreSearch } = useCommonStore()

const props = withDefaults(defineProps<{
  creditCode?: string | number
  params?: any
  editData?: any
  isDetail?: boolean
  caseId?: string | number
  custome?: boolean
  approvalStatus?: string | number
}>(), {
  editData: {}
})

const emit = defineEmits(['save'])
const orgArchivesEl = ref(null)
const loading = ref(false)
const model = ref({
  year: '',
  month: '',
})
const baseModel: any = shallowRef({})
let moreNewsModel: any = ref({
  organizationInfoPO: {},
  staffPO: {},
  applicationContentXuanWuPO: {},
})
let modelData: any = ref({
  organizationInfoPO: {},
  staffPO: {},
  applicationContentXuanWuPO: {},
})

const drawer = ref(false)

const onClose = () => {
  setTempParams({})
  setGloablParams({})
  setMoreSearch({})
}

const getCurrentQuarter = (nowMonth?: number | string) => {
  const month: any = nowMonth || new Date().getMonth() + 1
  if (month >= 1 && month <= 3) {
    return '一'
  } else if (month >= 4 && month <= 6) {
    return '二'
  } else if (month >= 7 && month <= 9) {
    return '三'
  } else {
    return '四'
  }
}


const dataListBase = [
  [
    {
      m: '基 本 情 况',
      bl: 1,
      fs: 16,
      mc: {
        rs: 1,
        cs: 4,
      },
    },
  ],
  [
    { m: '机构名称', style: { width: '200px' } },
    {
      m: '',
      prop: 'organizationName',
      archives: true,
      setColor: true,
      archivesText: '档案',
      showLink: (col, model) => {
        orgArchivesEl.value?.getServiceOrgInfo(model.creditCode)
      },
    },
    { m: '法定代表人', style: { width: '200px' } },
    { m: '', prop: 'legalUserName', setColor: true },
  ],
  [{ m: '机构地址' }, { m: '', setColor: true, prop: 'organizationAddress' }, { m: '联系电话' }, { m: '', setColor: true, prop: 'legalUserPhone' }],
  [
    { m: '机构等级' },
    { m: '', prop: 'organizationLevelLabel', setColor: true },
    { m: '核定机构内床位数' },
    { setColor: true, m: '', prop: 'approvedBedTotal' },
  ],
  [
    { m: '核定符合省定标准的家庭养老床位数', mc: { rs: 1, cs: 2 } },
    { m: '', prop: 'standardBedNum', setColor: true, mc: { rs: 1, cs: 2 } },
  ],
  [
    { m: '营业执照（民非）证号' },
    { setColor: true, m: '', prop: 'orgHomeLicense' },
    { m: '机构设置证号（备案）' },
    { setColor: true, m: '', prop: 'filingCode' },
  ],
  [{ m: '开户银行' }, { setColor: true, m: '', prop: 'bankName' }, { m: '银行账号' }, { setColor: true, m: '', prop: 'bankAccount' }],
]
const dataListStaff = [
  [
    {
      m: '员 工 概 况',
      bl: 1,
      fs: 16,
      link: true,
      linkType: 'list',
      style: { borderTop: '0px solid #fff' },
      mc: {
        rs: 1,
        cs: 8,
      },
      showLink: (col, model) => {
        const creditCode = modelData.value.organizationInfoPO.creditCode
        setGloablParams({ creditCode: creditCode })
        drawer.value = true
      },
    },
  ],
  [
    { m: '员工总数' },
    { m: '', prop: 'staffTotalNumber' },
    { m: '持证人数' },
    { m: '', prop: 'staffCertificateNumber' },
    { m: '管理人员' },
    { m: '', prop: 'managerNumber' },
    { m: '持证人数' },
    { m: '', prop: 'managerCertificateNumber' },
  ],
]

const applyConfigBase = [
  [
    {
      m: '运营补贴申请内容',
      bl: 1,
      fs: 16,
      style: { borderTop: '0px solid #fff' },
      mc: {
        rs: 1,
        cs: 6,
      },
    },
  ],
  [
    {
      m: '月份',
      mc: {
        rs: 2,
        cs: 1,
      },
    },
    {
      m: '人数',
      mc: {
        rs: 2,
        cs: 1,
      },
    },
    {
      m: '金额（元）',
      mc: {
        rs: 2,
        cs: 1,
      },
    },
    
    {
      m: '政府养老扶助对象',
      mc: {
        rs: 1,
        cs: 2,
      },
    },
    {
      m: '补贴金额小计（元）',
      mc: {
        rs: 2,
        cs: 1,
      },
    },
  ],
  [{ m: '人' }, { m: '金额（元）' }],
]
const dataListApply: any = ref([
  ...applyConfigBase,
  [
    {
      m: '补贴金额',
      align: 'left',
      mc: {
        rs: 1,
        cs: 3,
      },
    },
    {
      m: '大写',
      align: 'left',
      mc: {
        rs: 1,
        cs: 6,
      },
    },
  ],
  [
    {
      m: '本机构承诺以上及所附数据资料真实有效，如有不实，愿承担相关处罚。',
      mc: {
        rs: 1,
        cs: 9,
      },
    },
  ],
])

const dataListFooter = [
  [
    {
      m: '审核意见',
      bl: 1,
      fs: 16,
      style: { borderTop: '0px solid #fff' },
      mc: {
        rs: 1,
        cs: 9,
      },
    },
  ],
  [
    {
      m: '区民政部门意见',
      mc: {
        rs: 1,
        cs: 2,
      },
    },
    {
      m: '',
      prop: 'opinion',
      mc: {
        rs: 1,
        cs: 7,
      },
    },
  ],
]

const getInitData = async () => {
  const params = props.params || {}
  const query = {
    year: '',
    month: '',
    creditCode: props.creditCode,
    projectId: props.params.subsidyProjectId,
  }
  if (params.belongDate) {
    query.year = params.belongDate.replace('年', '-').replace('月', '').split('-')[0]
    query.month = params.belongDate.replace('年', '-').replace('月', '').split('-')[1]
    model.value.year = query.year
    model.value.month = query.month
  } else {
    return
  }
  modelData.value = props.editData
  try {
    const condition = (props.caseId && props.isDetail) || props.custome || props.approvalStatus == -2
    loading.value = true
    let resultData = {}
    let uptoData = {}
    if (condition) {
      resultData = props.editData
    } else {
      uptoData = await apiMod.view_metadata_month_xw(query).then((res) => res.data)
      resultData = uptoData
    }
    baseModel.value = JSON.parse(JSON.stringify(resultData))
    const reportData = filterEmptyObj(resultData)

    if (uptoData.dataContent) {
      moreNewsModel.value = {
        isDataContent: 1,
        ...uptoData.dataContent,
        organizationInfoPO: {
          ...uptoData?.dataContent?.organizationInfoPO,
          viewStatus: uptoData?.viewStatus,
          isDataContent: 1,
        },
        staffPO: {
          ...uptoData?.dataContent?.staffPO,
          viewStatus: uptoData?.staffPO?.viewStatus,
          isDataContent: 1,
        },
        applicationContentXuanWuPO: {
          ...uptoData?.dataContent?.applicationContentXuanWuPO,
          isDataContent: 1,
        },
      }
    } else {
      moreNewsModel.value = {
        isDataContent: 1,
        organizationInfoPO: {
          viewStatus: uptoData?.viewStatus,
          isDataContent: 1,
        },
        staffPO: {
          viewStatus: uptoData?.staffPO?.viewStatus,
          isDataContent: 1,
        },
        applicationContentXuanWuPO: {
          isDataContent: 1,
        },
      }
    }

    let mixData = {
      ...props.editData,
      ...reportData,
      organizationInfoPO: {
        ...reportData.organizationInfoPO,
        ...props.editData.organizationInfoPO,
      },
      applicationContentXuanWuPO: {
        ...props.editData.applicationContentXuanWuPO,
        ...reportData.applicationContentXuanWuPO,
      },
      staffPO: {
        ...reportData.staffPO,
        ...props.editData.staffPO,
      },
    }
    if (!condition) {
      mixData.organizationInfoPO = {
        ...props.editData.organizationInfoPO,
        ...reportData.organizationInfoPO,
      }
      mixData.applicationContentXuanWuPO = {
        ...props.editData.applicationContentXuanWuPO,
        ...reportData.applicationContentXuanWuPO,
      }
      mixData.staffPO = {
        ...props.editData.staffPO,
        ...reportData.staffPO,
      }
    }
    loading.value = false
    let amass = mixData.applicationContentXuanWuPO?.amass

    const bigNum = mixData.applicationContentXuanWuPO.amass ? dealBigMoney(+mixData.applicationContentXuanWuPO.amass) : ''
    modelData.value = mixData
    if (!condition) handleSave()
    const applicationContentList = mixData.applicationContentXuanWuPO
      ? [mixData.applicationContentXuanWuPO].map((item) => {
        return [
          { m: `${item.mouth}月份`, prop: 'mouth' },
          { m: mixData.organizationInfoPO?.noRecipientsAssistanceNum,prop:'noRecipientsAssistanceNum' },
          { setColor: true, m: mixData.organizationInfoPO?.noRecipientsAssistanceMoney ,prop:'noRecipientsAssistanceMoney'},
          { setColor: true, m: mixData.organizationInfoPO?.recipientsAssistanceNum,prop:'recipientsAssistanceNum' },
          { setColor: true, m: mixData.organizationInfoPO?.recipientsAssistanceMoney,prop:'recipientsAssistanceMoney' },
          { setColor: true, m: mixData.organizationInfoPO?.subtotalSubsidyAmount ,prop:'subtotalSubsidyAmount'},
        ]
      })
      : []
    dataListApply.value = [
      ...applyConfigBase,
      ...applicationContentList,
      [
        {
          m: '补贴金额',
          align: 'left',
          propName: amass,
          mc: {
            rs: 1,
            cs: 5,
          },
        },
        {
          m: '大写',
          align: 'left',
          propName: bigNum,
          mc: {
            rs: 1,
            cs: 6,
          },
        },
      ],
      [
        {
          m: '本机构承诺以上及所附数据资料真实有效，如有不实，愿承担相关处罚。',
          prop: 'note',
          mc: {
            rs: 2,
            cs: 11,
          },
        },
      ],
    ]
  } catch (error) {
    loading.value = false
  }
}

watch(
  () => props.editData?.id,
  (val) => {
    if (val) {
      if (props.params) getInitData()
    }
  },
  {
    immediate: true,
  }
)


onMounted(() => {
  nextTick(() => {
    if (props.params) getInitData()
  })
})
const handleSave = () => {
  emit('save', modelData.value, 'xw_report_1001', props.editData)
}
</script>

<style scoped lang="scss">
.flex-column {
  display: flex;
  flex-flow: column;
  justify-content: space-around;
  height: 100px;
}

.text-underline {
  text-decoration: underline;
  padding: 0 6px;
}

.report-table-wrapper {
  width: 100%;
  margin: 0 auto;
  padding: 10px 30px;
  top: 0;

  .r-header {
    text-align: center;
    font-size: 18px;
    font-weight: bold;
    padding: 15px 0;

    .text-sm {
      font-weight: 400;
      font-size: 16px;
    }
  }
}
</style>
